package hn.sigit.view;

import hn.sigit.model.ladm.special.Rational;

public class ShareValue {
	private int numerator;
	private int denominator;
	
	public ShareValue() {
		setDefault();
	}
	public ShareValue(int numerator, int denominator) {
		this.numerator = numerator;
		this.denominator = denominator;
		
		this.simplify();
	}
	public ShareValue(Rational r) {
		if (r != null) {
			this.numerator = r.getNumerator();
			this.denominator = r.getDenominator();
			
			this.simplify();
		}
		else
			setDefault();
	}
	
	private void setDefault() {
		this.numerator = 0;
		this.denominator = 1;		
	}
	
	public int getNumerator() {
		return numerator;
	}
	public void setNumerator(int numerator) {
		this.numerator = numerator;
	}
	
	public int getDenominator() {
		return denominator;
	}
	public void setDenominator(int denominator) {
		this.denominator = denominator;
	}
	
	public ShareValue add(ShareValue other) {
		ShareValue r = new ShareValue();
		r.setNumerator(this.numerator * other.denominator + other.numerator * this.denominator);
		r.setDenominator(this.denominator * other.denominator);
		r.simplify();
		
		return r;
	}
	
	public void addOther(ShareValue other) {
		numerator = this.numerator * other.denominator + other.numerator * this.denominator;
		denominator = this.denominator * other.denominator;
		
		simplify();
	}
	
	public String toString() {
		return String.format("%d/%d", numerator, denominator);
	}
	
	public Rational asLadmRational() {
		return new Rational(numerator, denominator);
	}
	
	private void simplify() {
		int gcd = _gcd(numerator, denominator);
		
		numerator /= gcd;
		denominator /= gcd;
	}
	
	private int _gcd(int u, int v) {
		int r, res;
		
		while (true) {
			if (v == 0) {
				res = u;
				break;
			}
			else {
				r = u % v;
				u = v;
				v = r;
			}
		}
		
		return res;
	}
}
